
<template>
  <view class="container">
    <image mode="widthFix" class="preview-image" src="/static/image/success.jpg"></image>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';

const platform = ref(process.env.VUE_APP_PLATFORM);
const videoId = ref('cameraVideo');
const canvasId = ref('cameraCanvas');
const videoSrc = ref('');
const canvasWidth = ref(300);
const canvasHeight = ref(200);
const previewImage = ref('');
const showVideo = ref(false);
const videoContext = ref(null);
const canvasContext = ref(null);

const startCamera = async () => {
  // H5获取摄像头
  if (platform.value === 'h5') {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ 
        video: true,
        audio: false 
      });
      // 正确用法
      // const stream = await navigator.mediaDevices.getUserMedia({video: true});
      console.log('stream:', stream);
      const url = window.URL.createObjectURL(new MediaStream([stream.getVideoTracks()[0]]));
      console.log('url:', url);
      videoSrc.value = url;
      //   videoSrc.value = URL.createObjectURL(stream);
      showVideo.value = true;
    } catch (err) {
      console.error('摄像头访问失败:', err);
    }
  }
  // 小程序获取摄像头
  else if (platform.value === 'mp-weixin') {
    const ctx = uni.createCameraContext();
    ctx.start({
      success: () => showVideo.value = true,
      fail: (err) => console.error('摄像头启动失败:', err)
    });
  }
};

const initVideo = () => {
  if (platform.value === 'mp-weixin') {
    videoContext.value = uni.createVideoContext(videoId.value);
    canvasContext.value = uni.createCanvasContext(canvasId.value);
  }
};

const captureFrame = () => {
  if (platform.value === 'h5') {
    const video = document.getElementById(videoId.value);
    const canvas = canvasRef.value.$el;
    const ctx = canvas.getContext('2d');
    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
    previewImage.value = canvas.toDataURL('image/jpeg');
  } 
  else if (platform.value === 'mp-weixin') {
    canvasContext.value.drawImage(videoId.value, 0, 0, canvasWidth.value, canvasHeight.value);
    canvasContext.value.draw(false, () => {
      uni.canvasToTempFilePath({
        canvasId: canvasId.value,
        success: (res) => previewImage.value = res.tempFilePath
      });
    });
  }
};
</script>

<style>
.container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.preview-image {
  width: 40px;   
  height: auto;
  margin-top: 60px;
}
.canvas-element {
  margin: 15px 0;
  background-color: #f0f0f0;
}
.preview-image {
  width: 200px;
  height: 150px;
  margin-top: 15px;
  border: 1px solid #eee;
}
button {
  margin: 10px;
  padding: 8px 16px;
}
</style>
